from fastapi import APIRouter
from fastapi import FastAPI, Request
from app.controllers.orders.list import orders_list_controller
from app.controllers.orders.water import orders_water_controller
from app.controllers.orders.wechat import wechat_controller
from fastapi.responses import Response
import xmltodict

from app.core.websocket_manager import manager
from app.models import OrdersList
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.orders import SendMessage, OrdersWaterCreate

mini_notify_router = APIRouter()
model_name = "微信相关"

# 自定义的 XMLResponse 类
class XMLResponse(Response):
    def __init__(self, content: str, **kwargs):
        super().__init__(content=content, media_type="application/xml", **kwargs)

@mini_notify_router.post("/notify", summary=f"支付回调")
async def wechat_pay_callback(request: Request):
    ret =  wechat_controller.notify(headers = request.headers,data = await request.body())
    if ret["notify_status"] == 1:
        out_trade_no = ret["out_trade_no"]
        order = await OrdersList.filter(water_no=out_trade_no).first().values("id","address_id")
        orders_water = OrdersWaterCreate(
            order_id = order['id'],
            amount = ret['amount'],
            space_id=order['address_id'],
            out_trade_no = out_trade_no,
            transaction_id = ret['transaction_id'],
            success_time = ret['success_time'],
        )
        ##插入流水
        await orders_water_controller.do_create(orders_water)
        ##设置支付成功状态
        ret = await orders_list_controller.order_success(out_trade_no=out_trade_no)
        if ret["pay_status"] == 1:
            result_code = "SUCCESS"
            message = "OK"
        else:
            ##订单错误，需要自动退款掉
            await orders_list_controller.order_refund(order_id=order['id'], order_status=4)

    result_code = "SUCCESS"
    message = "OK"

    # 返回给微信的响应
    return XMLResponse(
        content=f"<xml><return_code><![CDATA[{result_code}]]></return_code><return_msg><![CDATA[{message}]]></return_msg></xml>",
        status_code=200)



@mini_notify_router.post("/send_message", summary=f"发送消息")
async def send_order_complete_notify(
    data_in: SendMessage,
):
    # 发送通知
    await wechat_controller.send_order_message(data_in=data_in)
    return Success(msg="发送成功")

@mini_notify_router.post("/send_message_admin", summary=f"发送消息给后端")
async def send_order_complete_notify_admin():
    # 发送通知
    await manager.notify_clients(f"您有一个新的订单:10001")
    return Success(msg="发送成功")

